package top.chenziji.Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class VideoUtils {

    // 获取视频的时长（以秒为单位）
    public static double getVideoDuration(String videoPath) throws IOException {
        ProcessBuilder processBuilder = new ProcessBuilder("ffmpeg", "-i", videoPath);
        Process process = processBuilder.start();

        // 获取FFmpeg的输出，获取时长信息
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String line;
        double duration = 0.0;
        while ((line = reader.readLine()) != null) {
            if (line.contains("Duration")) {
                // 找到包含 Duration 的行，格式为 "Duration: 02:12:47.25"
                String durationStr = line.split(",")[0].replaceAll(" ","").replaceAll("Duration:",""); // 通过空格和逗号提取出时长部分

                // 提取时、分、秒部分
                String[] parts = durationStr.split(":");
                // 时、分、秒、毫秒
                int hours = Integer.parseInt(parts[0]);
                int minutes = Integer.parseInt(parts[1]);
                String[] secondsParts = parts[2].split("\\."); // 分离秒和毫秒
                int seconds = Integer.parseInt(secondsParts[0]);
                double milliseconds = Double.parseDouble("0." + secondsParts[1]);

                // 将时长转换为总秒数
                duration = hours * 3600 + minutes * 60 + seconds + milliseconds;
                break;
            }
        }
        return duration;
    }
}

